package com.sctvcloud.dongqu.ui.activities;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.canyinghao.canrefresh.other.CanRecyclerViewHeaderFooter;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.DensityUtil;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Cache;
import com.sctvcloud.dongqu.base.BaseDetailActivity;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.beans.FComment;
import com.sctvcloud.dongqu.ui.adapter.CommentAdapter;
import com.sctvcloud.dongqu.ui.dialog.CommentDiaFragment;
import com.sctvcloud.dongqu.ui.util.RBaseItemDecoration;
import com.sctvcloud.dongqu.ui.utils.TitleUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 评论列表页
 */
public class CommentActivity extends BaseDetailActivity implements CanRefreshLayout.OnRefreshListener
        , CanRecyclerViewHeaderFooter.OnLoadMoreListener {
    @BindView(R.id.comment_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView comment_list;
    @BindView(R.id.comment_footer)
    protected CanRecyclerViewHeaderFooter footer;
    @BindView(R.id.comment_foot_pb)
    protected ProgressBar pb;
    @BindView(R.id.comment_foot_loadmore)
    protected View allLoaded;
    private LinearLayoutManager manager;
    private CommentAdapter adapter;
    private FComment fComment;
    private CommentDiaFragment commentDiaFragment;
    public static final String COMMENT_TAG = "dia_comment_fragment";
    private int pos = -1; //-1为写评论  其他为回复评论
    private String id;
    private int capacity = 20;//请求数据条数
    private int indexNumber = 0;
    private int requestType = 1;// 1代表新闻评论  2专题评论
    private int commentType = 0;   //0新闻评论  1专题评论 2 直播评论
    protected String baseConstUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_comment);
        ButterKnife.bind(this);
    }

    private void initView() {
        refreshLayout.setOnRefreshListener(this);

        boolean isCityState = getIntent().getBooleanExtra(Constances.IS_CITY_STATE, false);
        if (isCityState) {
            //泸州新闻动态接口域名
            baseConstUrl = Cache.getInstance().getChoosedCityStUrl();
        }

        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        comment_list.setItemAnimator(new DefaultItemAnimator());
        comment_list.setLayoutManager(manager);
//        comment_list.addItemDecoration(new RBaseItemDecoration(DensityUtil.dip2px(this, 1),
//                ContextCompat.getColor(this, R.color.colorItemListDivider)));
//        boolean b=getIntent().hasExtra("id");
//        JLog.e("has id extra "+b);
        id = getIntent().getStringExtra(EX_ID);
        requestType = getIntent().getIntExtra(EX_TYPE_NEWS, 1);
        commentType = getIntent().getIntExtra(EX_COMMENT_TYPE, -1);

        footer.attachTo(comment_list, false);
        footer.setLoadMoreListener(this);
        footer.setVisibility(View.GONE);

        refreshLayout.autoRefresh();
    }

    @OnClick(value = {R.id.comment_write_comment})
    public void commentClick(View view) {
        if (TextUtils.isEmpty(baseConstUrl)) {
            showCommentDialog(id, null, commentType);  //0代表新闻评论
        } else {
            showCommentDialog(id, true, null, commentType);  //0代表新闻评论
        }
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            footer.loadMoreComplete();
        } else {
            indexNumber += 20;
//            getCommentNews(id, requestType, capacity, indexNumber);
            if (TextUtils.isEmpty(baseConstUrl)) {
                getCommentNews(id, requestType, capacity, indexNumber);
            } else {
                getCommentNews(id, baseConstUrl, requestType, capacity, indexNumber);
            }
        }
    }

    @Override
    public void onChildAttached(View v) {
    }

    @Override
    public void onRefresh() {
        capacity = 20;
        indexNumber = 0;
        if (TextUtils.isEmpty(baseConstUrl)) {
            getCommentNews(id, requestType, capacity, indexNumber);
        } else {
            getCommentNews(id, baseConstUrl, requestType, capacity, indexNumber);
        }
//        getCommentNews(id, requestType, capacity, indexNumber);
    }

    /**
     * 获取全部数据
     *
     * @param ca
     */
    private void requestAll(int ca) {
        capacity = ca;
        indexNumber = 0;
        if (TextUtils.isEmpty(baseConstUrl)) {
            getCommentNews(id, requestType, capacity, indexNumber);
        } else {
            getCommentNews(id, baseConstUrl, requestType, capacity, indexNumber);
        }
//        getCommentNews(id, requestType, capacity, indexNumber);
    }

    @Override
    protected void onCommentGetListSuc(int count, List<FComment> fProgrammes) {
        super.onCommentGetListSuc(count, fProgrammes);
        if (indexNumber >= count || count <= capacity) {
            footer.setLoadEnable(false);
            pb.setVisibility(View.GONE);
            allLoaded.setVisibility(View.VISIBLE);
            initInfo(fProgrammes);
        } else {
            requestAll(count);
//            if (!footer.isLoadEnable()) {
//                footer.setLoadEnable(true);
//                pb.setVisibility(View.VISIBLE);
//                allLoaded.setVisibility(View.GONE);
//            }
        }


    }

    @Override
    protected void onCommentNetFinish(int mode, boolean isNetSuc) {
        if (mode == Constances.MODE_COMMENT_GET_NEW) {
            onNetFinish();
        }
        super.onCommentNetFinish(mode, isNetSuc);
    }

    @Override
    protected void onCommentSendSuc(int mode) {
        super.onCommentSendSuc(mode);
        onRefresh();
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        } else {
            footer.loadMoreComplete();
        }


    }

    private void initInfo(List<FComment> datas) {
        List<FComment> data = dataHandle(datas);
        if (adapter == null) {
            adapter = new CommentAdapter(this, data);
            adapter.setItemInternalClick(commentItemClick);
            comment_list.setAdapter(adapter);
        } else {
            if (indexNumber == 0) {
                adapter.setData(data);
            } else {
                adapter.addDatas(data);
            }
        }
        if (adapter.getItemCount() == 0) {
            footer.setVisibility(View.GONE);
        } else {
            footer.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 处理评论数据
     *
     * @param datas
     * @return
     */
    private List<FComment> dataHandle(List<FComment> datas) {
        List<FComment> comments = new ArrayList<>();
        List<FComment> answers = new ArrayList<>();
        if (null != datas) {
            FComment comment;
            for (int i = 0; i < datas.size(); i++) {
                comment = datas.get(i);
                if (TextUtils.isEmpty(comment.getAnswerTo())) {
                    comments.add(comment);
                } else {
                    answers.add(comment);
                }
            }

            for (int j = 0; j < answers.size(); j++) {
                FComment co = answers.get(j);
                for (int k = 0; k < comments.size(); k++) {
                    if (!TextUtils.isEmpty(co.getAnswerToCommentId()) && co.getAnswerToCommentId().equalsIgnoreCase(comments.get(k).getCommentId())) {
                        comments.add(k + 1, co);
                        break;
                    }
                }
            }
        }
        return comments;

    }

    private OnItemInternalClick commentItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
//            FComment comment = null;
//            if (view == null) {
//                comment = (FComment) itemView.getTag(R.id.adapter_item_data_key);
//            } else {
//                comment = (FComment) itemView.getTag(R.id.adapter_item_data_key);
//            }
            FComment comment = adapter.getItem(position);
            if (!TextUtils.isEmpty(comment.getCommentId())) {
                if (TextUtils.isEmpty(baseConstUrl)) {
                    showCommentDialog(id, comment.getCommentId(), commentType);
                } else {
                    showCommentDialog(id, true, comment.getCommentId(), commentType);
                }

            } else {
                toast("评论id为空");
            }
            //showCommentDialog(id, comment.getCommentId(), commentType);
        }
    };
}
